package com.vessel.decoration.mvp.presenter.mine.manage;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.miguelbcr.ui.rx_paparazzo2.RxPaparazzo;
import com.miguelbcr.ui.rx_paparazzo2.entities.FileData;
import com.miguelbcr.ui.rx_paparazzo2.entities.Response;
import com.vessel.decoration.app.constant.Constants;
import com.vessel.decoration.app.data.entity.VariableResponse;
import com.vessel.decoration.mvp.contract.mine.manage.SkillContract;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

import static android.app.Activity.RESULT_OK;

/**
 * @author vesselzhang
 * @date 2017/12/5
 */

@ActivityScope
public class SkillPresenter extends BasePresenter<SkillContract.Model, SkillContract.View> {
    private RxErrorHandler mErrorHandler;
    private Application mApplication;
    private AppManager mAppManager;

    private String avatarUri;

    @Inject
    public SkillPresenter(SkillContract.Model model, SkillContract.View rootView
            , RxErrorHandler handler, Application application, AppManager appManager) {
        super(model, rootView);
        this.mErrorHandler = handler;
        this.mApplication = application;
        this.mAppManager = appManager;
    }

    public void addImage() {
        CharSequence[] items = {"相册", "相机"};
        new AlertDialog.Builder(mAppManager.getCurrentActivity())
                .setTitle("选择图片来源")
                .setItems(items, (dialog, which) -> {
                    if (which == Constants.SELECT_ITEM_0) {
                        RxPaparazzo.single(mAppManager.getCurrentActivity())
                                .usingGallery()
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new AvatarPick());
                    } else {
                        RxPaparazzo.single(mAppManager.getCurrentActivity())
                                .usingCamera()
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new AvatarPick());
                    }
                })
                .create().show();
    }

    public void delete(int id) {
        mModel.removeSkill(id)
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(
                        new ErrorHandleSubscriber<Boolean>(mErrorHandler) {
                            @Override
                            public void onNext(Boolean aBoolean) {
                                mRootView.showMessage("删除成功");
                                mRootView.killMyself();
                            }
                        }
                );
    }

    public void submit(int id, String name, String price, String remark) {
        if (TextUtils.isEmpty(name) | TextUtils.isEmpty(price) | TextUtils.isEmpty(remark)) {
            mRootView.showMessage("请先完善资料");
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("skillName", name);
        map.put("price", price);
        if (!TextUtils.isEmpty(avatarUri)) {
            map.put("skillPic", avatarUri);
        }
        if (id != -1) {
            map.put("skillId", id);
        }
        if (!TextUtils.isEmpty(remark)) {
            map.put("remark", remark);
        }
        mModel.saveSkill(map)
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(
                        new ErrorHandleSubscriber<Boolean>(mErrorHandler) {
                            @Override
                            public void onNext(Boolean aBoolean) {
                                mRootView.showMessage("更新成功");
                                mRootView.killMyself();
                            }
                        }
                );
    }

    private void uploadFile(File file) {
        mModel.uploadFile(file)
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(
                        new ErrorHandleSubscriber<VariableResponse>(mErrorHandler) {
                            @Override
                            public void onNext(VariableResponse variableResponse) {
                                avatarUri = variableResponse.getUrl();
                                if (!TextUtils.isEmpty(avatarUri)) {
                                    mRootView.showPic(avatarUri);
                                }
                            }
                        }
                );
    }

    public void setUri(String uri) {
        this.avatarUri = uri;
    }

    private class AvatarPick implements Observer<Response<Activity, FileData>> {

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(Response<Activity, FileData> activityFileDataResponse) {
            if (activityFileDataResponse.resultCode() != RESULT_OK) {
                mRootView.showMessage("您取消了获取图片");
                return;
            }
            uploadFile(activityFileDataResponse.data().getFile());
        }

        @Override
        public void onError(Throwable e) {
            Log.e("error", e.toString());
        }

        @Override
        public void onComplete() {

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mApplication = null;
    }
}